<?php

namespace app\advertisement\logic;

use think\facade\Db;
use think\facade\Cache;
use util\Excel;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;
use think\cache\driver\Redis;

class AdvaccountLogic
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new \app\advertisement\model\Advaccount();
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {

        $advertiser_id = $params['advertiser_id'] ?? [];
        $admin_id = $params['admin_id'] ?? [];
        $shop_id = $params['shop_id'] ?? '';
        $platform_id = $params['platform_id'] ?? '';
        $group_id    = $params['groupId'] ?? '';
        $adminId     = $params['adminId'] ?? '';

        $limit = $params['limit'] ?? 10;
        $where = [];

        if(!empty($admin_id)){
            $where['b.admin_id'] = $admin_id;
        }
        if(!empty($shop_id)){
            $where['b.shop_id'] = $shop_id;
        }
        if(!empty($advertiser_id)){
            $where[] = ['a.advertiser_id', 'like', '%' . $advertiser_id . '%'];
        }
        if(!empty($platform_id)){
            $where['a.platform_id'] = $platform_id;
        }

        // update 2024-10-28
        if(in_array($group_id,[11,17,20,19])){
            $where['b.admin_id'] = $adminId;
        }

        $ProxyOwnership = $params['ProxyOwnership'] ?? '';
        if (!empty($ProxyOwnership)) {
            $where['a.ProxyOwnership'] = $ProxyOwnership;
        }

        $list = Db::name('advaccount')
            ->field('a.id,a.advertiser_id,a.platform_id,a.advertiser_name,a.info,
                b.shop_id,
                b.createtime,
                b.updatetime,a.status,
                c.nickname as admin_name,
                e.title as platform_title,a.ProxyOwnership
            ')
            ->alias('a')
            ->join('qu_advaccount_admin b','a.advertiser_id = b.advertiser_id and b.status=1', 'left')
            ->join('qu_system_admin c','c.id = b.admin_id', 'left')
            ->join('qu_advplatform e','e.id = a.platform_id', 'left')
            ->where($where)
            ->order("a.status desc,b.updatetime desc")
            ->group('a.id')
            ->paginate($limit);

        $lists = $list->items();

        $shop_ids = array_column($lists,'shop_id');
        $shop_ids = array_values(array_unique($shop_ids));
        $shop_info= Db::name('shops')->field('id,name')->whereIn('id',$shop_ids)->select();
        $shop_info= objectToArray($shop_info);
        $shop_info_map = array_column($shop_info,null,'id');

        //信息
        $adv_accountopening = Db::name('adv_accountopening')->field('id,title')->select()->toarray();
        $adv_proxyownership = Db::name('adv_proxyownership')->field('id,title')->select()->toarray();
        $accountopening_map = array_column($adv_accountopening,'title','id');
        $proxyownership_map = array_column($adv_proxyownership,'title','id');
        
        foreach ($lists as $k=>$v) {
            if(!empty($v['createtime'])){
                $lists[$k]['createtime'] = date('Y-m-d',$v['createtime']);
                if(!empty($v['updatetime'])){
                    $lists[$k]['updatetime'] = date('Y-m-d', $v['updatetime']);
                }else{
                    $lists[$k]['updatetime'] = "";
                }
            }else{
                $lists[$k]['createtime'] = "";
                $lists[$k]['updatetime'] = "";
            }
            $shop_infos = $shop_info_map[$v['shop_id']]??[];
            $lists[$k]['shop_name'] = $shop_infos['name']??'';
            //开户主体
            $lists[$k]['advertiser_name'] = $accountopening_map[$v['advertiser_name']]??"";
            //代理
            $lists[$k]['ProxyOwnership'] = $proxyownership_map[$v['ProxyOwnership']]??"";
        }
                
        $data = [
            'list'  => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $lists = [];
        $header = [];
        // $header[] = ['广告账户', 'advertiser_id'];
        $fileName = "export_Advaccount" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

    public function add($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $result = false;
        Db::startTrans();
        try {
            //广告账户
            $AdvertisingAccount['platform_id'] = $data['platform_id'] ?? 0;
            $AdvertisingAccount['info'] = $data['info'] ?? "";
            $AdvertisingAccount['advertiser_id'] = $data['advertiser_id'] ?? 0;
            $AdvertisingAccount['advertiser_name'] = $data['advertiser_name'] ?? 0;
            $AdvertisingAccount['ProxyOwnership'] = $data['ProxyOwnership'] ?? 0;
            $AdvertisingAccount['status'] = $data['status'] ?? 1;
            $AdvertisingAccount['updatetime_automatic'] = date('Y-m-d');
            $AdvertisingAccount['updatetime_automatic_last'] = date('Y-m-d');
            $AdvertisingAccount['created_at'] = date('Y-m-d H:i:s');
            $result = Db::name('advaccount')->insert($AdvertisingAccount);
            if ($result !== false) { 
                Db::commit();
                return json(DefaultResponse(200, true, '添加成功!', null));
            }
            Db::rollback();
            return json(DefaultResponse(201, false, '更新失败!', null));
        } catch (ValidateException $e) {
            Db::rollback();
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            Db::rollback();
            return json(DefaultResponse(201, false, '广告账户已存在!', null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));

    }

    public function find($id)
    {
        $where['a.id'] = $id;
        $row = Db::name('advaccount')
            ->field('a.id,a.advertiser_id,a.platform_id,a.advertiser_name,a.status,a.info,
                b.shop_id,
                b.createtime,
                b.updatetime,b.admin_id,a.ProxyOwnership
            ')
            ->alias('a')
            ->join('qu_advaccount_admin b','a.advertiser_id = b.advertiser_id and b.status = 1', 'left')
            ->where($where)
            ->order("b.status desc")
            ->find();

        if(!empty($row['createtime'])){
            $row['createtime'] = date('Y-m-d',$row['createtime']);
            if(!empty($row['updatetime'])){
                $row['updatetime'] = date('Y-m-d', $row['updatetime']);
            }else{
                $row['updatetime'] = "";
            }
        }else{
            $row['createtime'] = "";
            $row['updatetime'] = "";
        }
        $row['advertiser_name'] = (int)$row['advertiser_name'];
        $row['ProxyOwnership'] = (int)$row['ProxyOwnership'];
        if($row['ProxyOwnership'] == 0){
            $row['ProxyOwnership'] = "";
        }
        if($row['advertiser_name'] == 0){
            $row['advertiser_name'] = "";
        }
        if (empty($row)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }
        return json(DefaultResponse(200, true, '获取成功', $row));
    }

    public function edit($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $id = $data['id'];
        $row = $this->model->find($id);
        if (empty($row)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }
        $result = false;
        Db::startTrans();
        try {
            //广告账户
            $AdvertisingAccount['info'] = $data['info'] ?? "";
            $AdvertisingAccount['platform_id'] = $data['platform_id'] ?? 0;
            $AdvertisingAccount['advertiser_name'] = $data['advertiser_name'] ?? 0;
            $AdvertisingAccount['ProxyOwnership'] = $data['ProxyOwnership'] ?? 0;
            $AdvertisingAccount['status'] = $data['status'] ?? 0;

            $result = $row->save($AdvertisingAccount);
            if ($result) {
                Db::commit();
                return json(DefaultResponse(200, false, '更新成功!', null));
            }
            Db::rollback();
            return json(DefaultResponse(201, false, '更新失败!', null));
        } catch (ValidateException $e) {
            Db::rollback();
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            Db::rollback();
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
        Db::rollback();
        return json(DefaultResponse(200, false, '更新成功!', null));
    }

    // 广告归属修改
    public function edit_ascription($data = [])
    {
        $id = $data['id'] ?? 0;
        //广告归属
        if (empty($data['advertiser_id'])) {
            return json(DefaultResponse(201, false, '请添加广告账户!', null));
        }
        if (empty($data['admin_name'])) {
            return json(DefaultResponse(201, false, '请添加归属运营!', null));
        }
        if (empty($data['shop_id'])) {
            return json(DefaultResponse(201, false, '请添加归属店铺!', null));
        }
        if (empty($data['createtime'])) {
            return json(DefaultResponse(201, false, '请添加归属时间!', null));
        }
        //添加记录
        $AdvertisingAttribution['createtime'] = strtotime($data['createtime']);
        $AdvertisingAttribution['status'] = 1;
        $AdvertisingAttribution['advertiser_id'] = $data['advertiser_id'];
        $AdvertisingAttribution['admin_id'] = $data['admin_name'] ?? 0;

        //可能传过来的是姓名
        $AdvertisingAttribution['admin_id'] = Db::name('system_admin')->where(['nickname' => $data['admin_name']])->value('id') ?? $AdvertisingAttribution['admin_id'];

        $AdvertisingAttribution['shop_id'] = $data['shop_id'] ?? 0;

        if (!empty($data['updatetime'])) {
            $AdvertisingAttribution['status'] = 0;
            $AdvertisingAttribution['updatetime'] = strtotime($data['updatetime']);
            //广告归属时间是否重合
            $query_date = [
                'advertiser_id'  => $data['advertiser_id'],
                'end_time'  => $AdvertisingAttribution['updatetime'],
                'start_time'  => $AdvertisingAttribution['createtime'],
                'id'  => $id,
            ];
            $advaccount_admin = Db::name('advaccount_admin')  
                ->field('a.id,b.nickname')
                ->alias('a')
                ->join('qu_system_admin b','b.id = a.admin_id', 'left')
                ->where(function ($query) use ($query_date) {  
                    $query->where('a.createtime', '<', $query_date['end_time'])  
                        ->where('a.updatetime', '>', $query_date['start_time'])  
                        ->where('a.advertiser_id', '=', $query_date['advertiser_id'])
                        ->where('a.id',"<>",$query_date['id'])
                        ->where('a.status', '=', 0);  
                })  
                ->whereOr(function ($query) use ($query_date) {  
                    $query->where('a.createtime', '<', $query_date['end_time'])  
                    ->where('a.advertiser_id', '=', $query_date['advertiser_id'])
                    ->where('a.id',"<>",$query_date['id'])
                    ->where('a.status', '=', 1);  
                })
                ->select()->toArray();
            if(!empty($advaccount_admin)){
                $nickname = $advaccount_admin[0]['nickname'] ?? "未知";
                return json(DefaultResponse(201, false, '不能和'.$nickname.'的归属时间重合!', null));
            }
        }else{
            $AdvertisingAttribution['status'] = 1;
            $AdvertisingAttribution['updatetime'] = "";
            //广告归属人是否存在
            $advaccount_admin = Db::name('advaccount_admin')
                ->field('a.id,b.nickname')
                ->alias('a')
                ->join('qu_system_admin b','b.id = a.admin_id', 'left')
                ->where('a.advertiser_id',$data['advertiser_id'])
                ->where('a.status',1)
                ->where('a.id',"<>",$id)
                ->find();
            if(!empty($advaccount_admin)){
                $nickname = $advaccount_admin['nickname'] ?? "未知";
                return json(DefaultResponse(201, false, '该账户'.$nickname.'在用!', null));
            }
            //广告归属时间是否重合
            $advaccount_admin = Db::name('advaccount_admin')
                ->field('a.id,b.nickname')
                ->alias('a')
                ->join('qu_system_admin b','b.id = a.admin_id', 'left')
                ->where('updatetime',">",$AdvertisingAttribution['createtime'])
                ->where('a.advertiser_id',$data['advertiser_id'])
                ->where('a.status',0)
                ->where('a.id',"<>",$id)
                ->find();
            if(!empty($advaccount_admin)){
                $nickname = $advaccount_admin['nickname'] ?? "未知";
                return json(DefaultResponse(201, false, '不能和'.$nickname.'的归属时间重合!', null));
            }
        }
        
        // 操作日志
        $operator = $data['operator'] ?? 1;
        $insert = [
            'advertiser_id' => $AdvertisingAttribution["advertiser_id"] ?? 0,
            'admin_id' => $AdvertisingAttribution["admin_id"] ?? 0,
            'shop_id' => $AdvertisingAttribution["shop_id"] ?? 0,
            'createtime' => $AdvertisingAttribution["createtime"] ?? 0,
            'updatetime' => $AdvertisingAttribution["updatetime"] ?? 0,
            'operator' => $operator,
            'operatortime' => time(),
            'operatorinfo' => "edit",
        ];
        Db::name('advaccount_admin_log')->insert($insert);
        if (!empty($id)) {
            Db::name('advaccount_admin')->where('id', $id)->update($AdvertisingAttribution);
        }else{
            Db::name('advaccount_admin')->insert($AdvertisingAttribution);
            //获取新增数据的id
            $id = Db::name('advaccount_admin')->getLastInsID();
        }
        $return = [
            'id' => $id,
        ];
        return json(DefaultResponse(200, false, '更新成功!', $return));
    }

    // 广告归属删除
    public function del_ascription($data = [])
    {
        //删除
        $id = $data['id'] ?? 0;
        Db::name('advaccount_admin')->where('id',$id)->delete();
        
        // 操作日志
        $operator = $data['operator'] ?? 1;
        $insert = [
            'advertiser_id' => $AdvertisingAttribution["advertiser_id"] ?? 0,
            'admin_id' => $AdvertisingAttribution["admin_id"] ?? 0,
            'shop_id' => $AdvertisingAttribution["shop_id"] ?? 0,
            'createtime' => $AdvertisingAttribution["createtime"] ?? 0,
            'updatetime' => $AdvertisingAttribution["updatetime"] ?? 0,
            'operator' => $operator,
            'operatortime' => time(),
            'operatorinfo' => "delete",
        ];
        Db::name('advaccount_admin_log')->insert($insert);

        return json(DefaultResponse(200, false, '操作成功!', null));
    }
    
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc AscriptionList归属列表
     * @author zhangheng
     */
    public function AscriptionList($params = [])
    {
        $limit = $params['limit'] ?? 10;
        $advertiser_id = $params['advertiser_id'] ?? "";
        $admin_id = $params['admin_id'] ?? "";
        $shop_id = $params['shop_id'] ?? "";

        $where = [];
        if(!empty($advertiser_id)){
            $where[] = ['a.advertiser_id', '=', $advertiser_id];
        }
        if (!empty($admin_id)) {
            $where[] = ['admin_id', '=', $admin_id];
        }
        if (!empty($shop_id)) {
            $where[] = ['shop_id', '=', $shop_id];
        }
        
        $list = Db::name('advaccount_admin')
            ->field('
                a.id,
                a.advertiser_id,
                a.shop_id,
                a.createtime,
                a.updatetime,a.status,
                c.nickname as admin_name,
                d.name as shop_name
            ')
            ->alias('a')
            ->join('qu_system_admin c','c.id = a.admin_id', 'left')
            ->join('qu_shops d','d.id = a.shop_id', 'left')
            ->where($where)
            ->order("a.status desc,a.updatetime desc")
            ->paginate($limit);
        $lists = $list->items();
        foreach ($lists as $k=>$v) {
            $lists[$k]['createtime'] = date('Y-m-d',$v['createtime']);
            if(!empty($v['updatetime'])){
                $lists[$k]['updatetime'] = date('Y-m-d',$v['updatetime']);
            }else{
                $lists[$k]['updatetime'] = "";
            }
        }
        
        $data = [
            'list' => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }


    
    
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function Ascriptionexport($params = [])
    {
        $header = [];
        $header[] = ['广告ID', 'advertiser_id'];
        $header[] = ['归属人', 'admin_name'];
        $header[] = ['店铺', 'shop_name'];
        $header[] = ['归属开始时间', 'createtime'];
        $header[] = ['归属结束时间', 'updatetime'];
        $fileName = "Ascriptionexport" . time();
        
        $advertiser_id = $params['advertiser_id'] ?? "";
        $admin_id = $params['admin_id'] ?? "";
        $shop_id = $params['shop_id'] ?? "";

        $where = [];
        if(!empty($advertiser_id)){
            $where[] = ['a.advertiser_id', '=', $advertiser_id];
        }
        if (!empty($admin_id)) {
            $where[] = ['admin_id', '=', $admin_id];
        }
        if (!empty($shop_id)) {
            $where[] = ['shop_id', '=', $shop_id];
        }
        
        $lists = Db::name('advaccount_admin')
            ->field('
                a.id,
                a.advertiser_id,
                a.shop_id,
                a.createtime,
                a.updatetime,a.status,
                c.nickname as admin_name,
                d.name as shop_name
            ')
            ->alias('a')
            ->join('qu_system_admin c','c.id = a.admin_id', 'left')
            ->join('qu_shops d','d.id = a.shop_id', 'left')
            ->where($where)
            ->order("a.status desc,a.updatetime desc")
            ->select()->toarray();
        foreach ($lists as $k=>$v) {
            $lists[$k]['createtime'] = date('Y-m-d',$v['createtime']);
            if(!empty($v['updatetime'])){
                $lists[$k]['updatetime'] = date('Y-m-d',$v['updatetime']);
            }else{
                $lists[$k]['updatetime'] = "";
            }
        }
        
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

    /**
     * @desc   通过平台获取广告账户
     * @author luckyXiong
     * @date   2024-08-28
     */
    public function getAdvistementList($params=[]){
        $platform_id  =  $params['platform_id']??'';
        $where        =  [];
        if(!empty($platform_id)){
            $where['a.platform_id'] = $platform_id;
        }
        $list = Db::name('advaccount')
            ->field('a.advertiser_id,a.advertiser_name')
            ->alias('a')
            ->join('qu_advplatform e','e.id = a.platform_id', 'left')
            ->where($where)
            ->group('a.id')
            ->select();
        $lists = objectToArray($list);

        //信息
        $adv_accountopening = Db::name('adv_accountopening')->field('id,title')->select()->toarray();
        $accountopening_map = array_column($adv_accountopening,null,'id');
        
        foreach ($lists as $k=>$v) {
            $accountopening_infos = $accountopening_map[$v['advertiser_name']]??[];
            $lists[$k]['advertiser_name'] = $accountopening_infos['title']??$v['advertiser_name'];
        }

        return json(DefaultResponse(200, true, '获取成功', $lists));
    }
    
    
    
}
